from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from .models import ArticleType
from .models import Article
from .models import UserMsg
from .models import Comment
from img_db.models import IMG
import os
def index(request):
    '''
    主页的函数
    '''
    if request.session.has_key('name123213'):
        nav1 = request.session['name123213']
        nav2 = '/'
        nav3 = '退出'
        nav4 = '/logout'
    else:
        nav1 = '注册'
        nav2 = '/register'
        nav3 = '登录'
        nav4 = '/login'
    articletype = list(ArticleType.objects.values('articletype'))
    # 截取前20条进行显示
    article = Article.objects.values('aid', 'title', 'author_name', 'abstract', 'content')[:20]
    context = {
        'articletype': articletype,
        'article': article,
        'nav1': nav1,
        'nav2': nav2,
        'nav3': nav3,
        'nav4': nav4
    }
    return render(request, 'index.html', context=context)


def show_article(request, aid):
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    path = os.path.join(BASE_DIR, 'templates/static_html/')
    if os.path.exists(path=path + str(aid) + '.html') and request.method!='POST':
        return render(request, path + str(aid) + '.html')
    article = Article.objects.filter(aid__exact=aid)[0]
    if request.session.has_key('name123213'):
        nav1 = request.session['name123213']
        nav2 = '/'
        nav3 = '退出'
        nav4 = '/logout'
        if request.method == 'POST':
            comment = request.POST['content']
            Comment.objects.create(article_id=article, content=comment)
    else:
        nav1 = '注册'
        nav2 = '/register'
        nav3 = '登录'
        nav4 = '/login'
        if request.POST == 'POST':
            return HttpResponse('对不起，没有登录不能评论！')
    img = IMG.objects.filter(articleid__exact=article.title)
    # return HttpResponse(type(img))

    comment_content = Comment.objects.filter(article_id__exact=article).values('content')[:10]
    # 将该文章的插图找到
    context = {
        'nav1': nav1,
        'nav2': nav2,
        'nav3': nav3,
        'nav4': nav4,
        'article': article,
        'comment_content': comment_content,
    }
    if img:
        context['img'] = img[0]
    else:
        context['img'] = False
    return render(request, 'article.html', context=context)


def reg(request):
    '''
    注册的函数
    :param request:
    :return:
    '''
    if request.method == 'POST':
        name = request.POST['name']
        passwd = request.POST['passwd']
        email = request.POST['email']
        phone = request.POST['phone']
        if UserMsg.objects.filter(name__exact=name):
            return HttpResponse('对不起该用户已经被注册了！')
        UserMsg.objects.create(name=name, passwd=passwd, email=email, phone=phone, isadmin=False)
        return HttpResponse('注册成功')
    return render(request, 'register.html')


def login(request):
    '''
    登录的函数
    :param request:
    :return:
    '''
    if request.session.has_key('name123213'):
        return HttpResponseRedirect('/')
    if request.method == 'POST':
        name = request.POST['name']
        passwd = request.POST['passwd']
        islogin = UserMsg.objects.filter(name__exact=name, passwd__exact=passwd)
        if islogin:
            request.session['name123213'] = name
            return HttpResponseRedirect('/')
        else:
            return HttpResponse('登录失败')
    return render(request, 'login.html')


def logout(request):
    '''
    退出登录的函数
    :param request:
    :return:
    '''
    del request.session['name123213']
    return HttpResponseRedirect('/')


def publish(request):
    '''
    发布文章的函数
    :param request:
    :return:
    '''
    if request.session.has_key('name123213') == False:
        return HttpResponseRedirect('/login')
    else:
        nav1 = request.session['name123213']
        nav2 = '/'
        nav3 = '退出'
        nav4 = '/logout'
    # 查询出所有文章类别的ID和名称
    typeall = ArticleType.objects.values('id', 'articletype')
    typeid = []
    typename = []
    for item in typeall:
        typeid.append(item['id'])
        typename.append(item['articletype'])
    typeidandname = zip(typeid, typename)

    # 查找用户是不是管理员
    thisuser = list(UserMsg.objects.filter(name=request.session['name123213']).values())[0]
    isadmin = thisuser['isadmin']
    if isadmin is False:
        return HttpResponse('对不起！您不是管理员不能发布文章')
    if request.method == 'POST':
        thistitle = request.POST['title']
        author = request.POST['author']
        thisabstrct = request.POST['detail']
        thistype_name = request.POST['typeid']
        thiscontent = request.POST['content']
        new_img = IMG(img=request.FILES.get('img'), name=request.FILES.get('img').name, articleid=thistitle)
        new_img.save()
        typename = ArticleType.objects.get(articletype=thistype_name)
        Article.objects.create(title=thistitle, author_name=author, abstract=thisabstrct, content=thiscontent,
                               type=typename)
        return HttpResponse('文章发布成功！')
    context = {
        'typeidandname': typeidandname,
    }

    return render(request, 'publish.html', context=context)

def static_all(request, thepage):
    import urllib.request
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    path = os.path.join(BASE_DIR, 'templates/static_html/')
    for i in range(0, int(thepage)):
        try:
            url = 'http://127.0.0.1:8000/articles/' + str(i)
            urllib.request.urlretrieve(url, filename=path + str(i) + '.html')
        except Exception as e:
            print('exception',e)
    return HttpResponse('静态化处理成功！')
